// pages/insurPlan/insurPlan.js
import config from "../../config.js";

const openIdUrl = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: 0,
    longitude: 0,
    address: "",
    confirmType: 1,
    houseKeeperId: '',
    tabs: [{
      text: "车险方案",
      price: ""
    }],
    defaultKeeper: {
      name: '',
      header: '',
      houseKeeperId: null
    },
    checkStr: "",
    numIndex: 0,
    insuranceItems: [],
    activeIndex: 0,
    itemLast: [],
    itemNow: [],
    items: '',
    againId: 0,
    orderId: -1
  },
  getItemsList: function() {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })

    wx.request({
      url: openIdUrl.insuranceItems,
      data: {
        start: 0,
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          that.setData({
            insuranceItems: res.data.data
          })
          var items = [];
          if (that.data.againId == 1) {
            items = wx.getStorageSync("againPlan");
            console.log(items);
          }

          console.log(that.data.insuranceItems);

          var itemLast = that.data.itemLast;
          var insuranceItemsOrinal = that.data.insuranceItems;
          for (var i = 0; i < insuranceItemsOrinal.length; i++) {
            var insuranceItems = insuranceItemsOrinal[i].insuranceItems;
            for (var j = 0; j < insuranceItems.length; j++) {
              var insuranceItem = insuranceItems[j];
              if (that.data.againId != 1) {
                if (insuranceItem.isChoose == 1) {
                  itemLast.push(insuranceItem.insuranceId)
                }
              } else {
                for (var z = 0; z < items.length; z++) {
                  var item = items[z];
                  if (item != null && insuranceItem.insuranceId == item.insuranceItem.insuranceId) {

                    insuranceItem.isChoose = 1;


                    if (item.deductible == 1) {
                      insuranceItem.deductible = 1;
                    }
                    if (item.insuranceKindNum != null) {
                      for (var x = 0; x < insuranceItem.insuranceKindNums.length; x++) {
                        var it = insuranceItem.insuranceKindNums[x];
                        if (it.numId == item.insuranceKindNum.numId) {
                          insuranceItem.numId = x;
                        }
                      }
                      console.log(insuranceItem.numId);
                    }

                    if (insuranceItem.isChoose == 1) {
                      itemLast.push(insuranceItem.insuranceId)
                    }

                    insuranceItems[j] = insuranceItem;
                    break;
                  } else {
                    insuranceItem.isChoose = 0;
                  }
                }
              }

            }
            insuranceItemsOrinal[i].insuranceItems = insuranceItems;
          }



          console.log(insuranceItemsOrinal);
          that.setData({
            itemLast: itemLast,
            insuranceItems: insuranceItemsOrinal
          })

          that.setData({
            itemNow: itemLast
          })
          //配置默认选项
          var itemStr = itemLast.join(",");

          that.setData({
            items: itemStr
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },
  appointment: function() {
    var that = this;
    /**wx.showLoading({
      title: '加载中...',
    })**/
    var user = wx.getStorageSync("user");
    if (this.data.houseKeeperId == "") {
      this.data.houseKeeperId = that.data.defaultKeeper.houseKeeperId;
    }

    var orderType = 1;
    var carId = wx.getStorageSync("carId");
    var comId = wx.getStorageSync("comId");
    var orderFrom = 1;
    if (this.data.confirmType == 2) {
      orderFrom = 2;
      user = wx.getStorageSync("userchoose");
      var car = wx.getStorageSync("carchoose");
      carId = car.cid;
    }

    //组织items
    var itemStr = that.data.itemNow.join(",");
    that.setData({
      items: itemStr
    })
    //使用json格式传输数据
    var jsonstrs = JSON.stringify(this.data.insuranceItems);
    wx.setStorageSync("againPlan", null);

    jsonstrs = '{"data":' + jsonstrs + '}';
    console.log(jsonstrs);

    if (that.data.items == "") {
      wx.showToast({
        title: '请至少选择一项保险项目！',
        icon: 'none',
        mask: true,
        duration: 1000
      })
      return false;

    }
    var uid = "";
    if (user != null) {
      uid = user.aid;
    }

    var idenCardA = wx.getStorageSync("idenCardA");
    var idenCardB = wx.getStorageSync("idenCardB");
    var licenseFr = wx.getStorageSync("licenseFr");
    var licenseBa = wx.getStorageSync("licenseBa");

    wx.request({
      url: openIdUrl.insuranceSubbmit,
      data: {
        userId: uid,
        orderId: that.data.orderId,
        idenCardA: idenCardA,
        idenCardB: idenCardB,
        licenseFr: licenseFr,
        licenseBa: licenseBa,
        houseKeeperId: this.data.houseKeeperId,
        orderType: orderType,
        carId: carId,
        comId: comId,
        address: this.data.address,
        locLatitude: this.data.latitude,
        locLongitude: this.data.longitude,
        orderFrom: orderFrom,
        items: jsonstrs,

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.status == 200) {
          wx.setStorageSync("orderId", res.data.data.oid);
          wx.setStorageSync("orderConfirmType", 1);
          if (that.data.confirmType == 1) {
            // wx.switchTab({
            //   url: "../order/order",
            // })
            var type = wx.getStorageSync("orderConfirmType");
            console.log(type);
            if (type != null && type == 1) {
              var orderId = wx.getStorageSync("orderId");
              // that.data.orderId = orderId;
              if (orderId) {
                wx.navigateTo({
                  url: "../orderSuccess/success?id=" + orderId,
                  complete: function() {
                    wx.setStorageSync("orderConfirmType", null);
                    wx.setStorageSync("orderId", null);
                  }
                })
              }
            }
          } else {
            wx.reLaunch({
              url: "../gjIndex/gjorder/gjorder",
            })

          }
          // wx.showModal({
          //   title: "恭喜您",
          //   content: "预约成功，车管家将会在10分钟内通过电话与您沟通详情 ，请保持电话畅通！谢谢！",
          //   showCancel: false,
          //   confirmColor: "#137AF0",
          //   success: function() {

          //   }
          // })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.data.message + "",
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }

      },
      error: function() {
        wx.showToast({
          title: "请求失败,请联系管理员",
          icon: 'none',
          mask: true,
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    var that = this;
    //判断下单类型
    var confirmType = options.confirmType;
    var againId = options.again;
    var orderId = options.orderId;
    if (againId == 1) {
      this.setData({
        againId: 1,
        orderId: orderId
      })
    }

    if (confirmType == null) {
      confirmType = 1;
    }
    this.setData({
      confirmType: confirmType
    })



    var user = wx.getStorageSync("user");
    console.log(user);

    if (user.housekeeper != null) {
      this.setData({
        "defaultKeeper.name": user.housekeeper.name,
        "defaultKeeper.houseKeeperId": user.housekeeper.keeperId,
        "defaultKeeper.header": user.housekeeper.image,
        houseKeeperId: options.keeperId != null ? options.keeperId : -1,
      })

    }
  },
  tabClick: function(e) {
    this.setData({
      activeIndex: e.currentTarget.id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    this.getItemsList();
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        console.log(res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.setStorageSync("houseKeeper", null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  checkChange: function(e) {
    var that = this;
    this.setData({
      itemLast: that.data.itemNow,
    })
    this.setData({
      itemNow: e.detail.value,
    })
    var dataArr1 = this.clone(this.data.itemLast);
    var dataArr2 = this.clone(this.data.itemNow);


    var left = that.differ(dataArr1, dataArr2);
    for (var z = 0; z < that.data.itemNow.length; z++) {
      var item = that.data.itemNow[z];
      for (var i = 0; i < that.data.insuranceItems.length; i++) {
        var insuranceItems = that.data.insuranceItems[i].insuranceItems;
        if (insuranceItems != null) {
          for (var j = 0; j < insuranceItems.length; j++) {
            var insuranceItem = insuranceItems[j];
            /**if (insuranceItem.insuranceId == item) {
              insuranceItem.isChoose = 1;
              insuranceItems[j] = insuranceItem;
              that.data.insuranceItems[i].insuranceItems = insuranceItems;
            }**/

            if (insuranceItem.insuranceId == Math.abs(left)) {
              if (left < 0) {
                insuranceItem.isChoose = 0;
              } else {
                insuranceItem.isChoose = 1;
              }
              insuranceItems[j] = insuranceItem;
              that.data.insuranceItems[i].insuranceItems = insuranceItems;
            }
          }
        }

      }
    }

  },
  /**第一个参数必须是上次选择时保存的数据 */
  differ: function(arr1, arr2) {
    var abs = arr1.length > arr2.length ? -1 : 1;
    var arrBiger = arr1.length > arr2.length ? arr1 : arr2;
    var arrSmall = arr1.length < arr2.length ? arr1 : arr2;

    var signal = false;
    for (var i = 0; i < arrBiger.length; i++) {
      var itemBiger = arrBiger[i];
      for (var j = 0; j < arrSmall.length; j++) {
        var itemSamller = arrSmall[j];
        if (itemBiger == itemSamller) {
          arrBiger.splice(i, 1);
          arrSmall.splice(j, 1);
          this.differ(arrBiger, arrSmall);
          signal = true;
        }
        if (signal) {
          break;
        }

      }
      if (signal) {
        break;
      }
    }


    return arrBiger[0] * abs;
  },
  clone: function(arr) {
    return JSON.parse(JSON.stringify(arr));
  },
  chooseLocation: function() {
    wx.chooseLocation({
      success(res) {
        console.log(res);
      },
      complete(res) {
        console.log(res);
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  deductibleAction: function(e) {
    var item = e.currentTarget.dataset.item;
    if (item.deductible == 1) {
      item.deductible = 0;
    } else {
      item.deductible = 1;
    }

    var data = this.data.insuranceItems;

    for (var i = 0; i < data.length; i++) {
      var it = data[i];
      if (it.insuranceItems != null) {
        for (var j = 0; j < it.insuranceItems.length; j++) {
          var insuranceItem = it.insuranceItems[j];
          if (insuranceItem.insuranceId == item.insuranceId) {
            if (item.deductible == 1) {
              item.isChoose = 1;
            }
            it.insuranceItems[j] = item;
            data[i] = it;

            break;
          }
        }
      }


    }

    this.setData({
      insuranceItems: data
    })
  },
  numChange: function(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    var numId = e.detail.value;

    item.numId = numId;

    for (var i = 0; i < that.data.insuranceItems.length; i++) {
      var insuranceItems = that.data.insuranceItems[i].insuranceItems;
      for (var j = 0; j < insuranceItems.length; j++) {
        var insuranceItem = insuranceItems[j];
        if (insuranceItem.insuranceId == item.insuranceId) {
          insuranceItems[j] = item;
          that.data.insuranceItems[i].insuranceItems = insuranceItems;
          break;
        }
      }
    }

    that.setData({
      insuranceItems: that.data.insuranceItems
    })
  }
})